/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.hourupdate.network.bean;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import org.apache.log4j.Logger;

import com.hourupdate.network.utils.Tools;


/**
 * @author Windows7
 * Servlet implementation class  LoginServlet
 * Program : LoginServlet
 * Create By : Wachiranon Aryuwong
 * Create Date : 19/05/2556
 * Modify By :
 * Modify Date :
 */
public class ExecuteSQLBean {
	static final Logger logger = Logger.getLogger(ExecuteSQLBean.class);
    /**
     *
     */
    public ExecuteSQLBean() {
    	
    }

    public ArrayList<Map<String, String>> executeQuery(PreparedStatement ps){
        ArrayList<Map<String, String>> list = new ArrayList<Map<String, String>>();
        ResultSet rs = null;
        ResultSetMetaData rsmd = null;
        try {
            rs = ps.executeQuery();
            rsmd = (ResultSetMetaData) rs.getMetaData();
            int colCount = rsmd.getColumnCount();
            
            int rowNum = 0;
            while (rs.next()) {
                //Represent Row Object
                Map<String, String> map = new HashMap<String, String>();
                for (int i = 1; i <= colCount; i++) {
                     map.put(rsmd.getColumnName(i).toUpperCase(), Tools.chkNull(rs.getString(i)));
                }
                list.add(rowNum, map);
                //Represent Table Object
                rowNum++;
            }//End Records
            
        } catch (Exception e) {
            logger.error(e.getMessage());
        } finally {
            try {
                if (rs != null) {
                    rs.close();
                }
            } catch (Exception e) {
            	logger.error(e.getMessage());
            }
        }
        return list;
    }
    
    public boolean executeStatement(PreparedStatement ps){
    	int success = 0;
    	try {
    		success = ps.executeUpdate();
		} catch (SQLException e) {
			logger.error(e.getMessage());
		}
    	return success > 0?true:false;
    }
}
